import 'package:dio/dio.dart';
import 'package:flutter_demo/utils/Event.dart';
import './TokenManager.dart';

class Http {
  final Dio _dio = Dio(
    BaseOptions(
      connectTimeout: Duration(seconds: 20),
      sendTimeout: Duration(minutes: 20),
      baseUrl: 'https://slwl-api.itheima.net',
    ),
  );

  Http() {
    _dio.options.headers['Content-Type'] = 'application/json';
    _addInterceptors();
  }

  _addInterceptors() {
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (request, handle) {
          String token = TokenManager().getToken();
          if (token.isNotEmpty) {
            request.headers['Authorization'] = token;
          }
          return handle.next(request);
        },
        onResponse: (response, handler) {
          return handler.next(response);
        },
        onError: (error, handler) {
          return handler.next(error);
        },
      ),
    );
  }

  Future<dynamic> get(String path, Map<String, dynamic>? params) async {
    try {
      final response = await _dio.get(path, queryParameters: params);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  Future<dynamic> post(String path, Map<String, dynamic> data) async {
    try {
      final response = await _dio.post(path, data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  Future<dynamic> put(String path, Map<String, dynamic> data) async {
    try {
      final response = await _dio.put(path, data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  dynamic handleResponse(Response response) {
    if (response.statusCode! >= 200 && response.statusCode! <= 300) {
      return response.data;
    } else {
      if (response.statusCode! == 401) {
        eventBus.fire(TokenInvalidEvent());
      }
      throw Exception('请求数据失败,$response.statusCode!');
    }
  }

  dynamic handleError(error) {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        throw Exception('响应错误，状态码：${error.response?.statusCode}');
      } else {
        throw Exception('网络请求错误：$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }
}

final Http http = Http();
